package paper.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import keter.util.IOUtil;

import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import paper.dao.TopicDao;
import paper.dao.UserDao;
import paper.domain.AuditStatus;
import paper.domain.User;
import paper.domain.Topic;
import paper.service.TopicService;
import paper.util.ConfigConstant;

@Service
public class TopicServiceImpl implements TopicService{
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(Service.class);

	@Autowired
    private TopicDao dao;
    
	@Override
    public TopicDao getTopicDao() {
		return dao;
	}
    
    @Autowired
    private UserDao udao;

    @Override
    public void save(Topic topic) {
        User user = udao.findOne(topic.getCreatorId());
        //教师创建的课题
        if(user.getAccount().hasRole("TEACHER")){
            //教师为负责人
            topic.setMaster(user);
            //状态：通过
            topic.setStatus(AuditStatus.PASS.toString());
        }
        else{
            //学生创建的课题
            //学生为完成人
            topic.setFinisher(user);
            //教师为负责人
            topic.setMaster(user.getTeacher());
            //状态：编辑
            topic.setStatus(AuditStatus.EDIT.toString());
        }
        dao.save(topic);
    }

    /**
     * <p>Method ：submitTopic
     * <p>Description : (学生)提交课题
     *
     * @param topic 
     * @author  顾力行-gulixing@msn.com
     */
    @Override
    public void submit(Topic topic) {
    	topic.setSubmitted(new Date());
        topic.setStatus(AuditStatus.SUBMIT.toString());
        dao.save(topic);
    }
    
    /**
     * <p>Method ：dispatchTopic
     * <p>Description :
     * 课题分配：分配后相当于将课题的一个副本交给学生进行维护
     * 对原课题的修改不会影响分配后课题的内容。
     * @param topic
     * @param studentList 
     * @author  gulixing@msn.com
     * @version 1.0.0
     */
    public  void dispatchTopic(Topic topic, List<User> studentList){   
        for (Iterator<User> iterator = studentList.iterator(); iterator.hasNext();) {
            User s = (User) iterator.next();
            Topic t = (Topic) topic.clone();
            t.setFinisher(s);
            dao.save(t);
        }
    }
    
    public void writeFile(User account, String fileName, InputStream inputStream) throws IOException{
        fileName = getReportStoreDir(account) + fileName;
        logger.info("写入文件:{}", fileName);
        FileUtils.copyInputStreamToFile(inputStream, new File(fileName));        
    }
    
    /**
     * <p>Method ：getStoreDir
     * <p>Description : 开题报告存储目录逻辑
     * {系统目录}
     * @param stu
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    private String getReportStoreDir(User stu){
        String path = ConfigConstant.getFileStoreRootPath();
        DateTime dt = new DateTime();
        path = path.concat(ConfigConstant.REPORT_SAVE_PATH) //开题报告子目录
               .concat(dt.getYear()+"/")//当前年
               .concat(stu.getDegree()+"/")//学位
               .concat(stu.getAccount().getUnit().getCode()+"/")//组织机构代码
               .concat(stu.getAccount().getName()+"/");//账户名称
        if(!new File(path).exists()){
            new File(path).mkdirs();
        }
        return path;
    }
    
    /**
     * <p>Method ：deleteMyTopic
     * <p>Description : 只允许删除本人创建的课题
     * @param id
     * @param creatorAccountId 
     * @author  gulixing@msn.com
     * @version 1.0.0
     */
    public void deleteMyTopic(Long id,Long creatorAccountId){
//        logger.info("the same is:{}",getTopicDao().findOne(id).getCreatorId()==creatorAccountId);
    	if(!getTopicDao().findOne(id).getCreatorId().equals(creatorAccountId)){
			logger.error("用户id:[{}]尝试删除非本人创建的课题",creatorAccountId);
			return;
		}
    	dao.deleteTopic(id);
    }

	@Override
	public void confirm(Topic topic) {
		dao.save(topic);
	}
}

